<template>
    <el-container class="stock_transfer_form_container">
        <el-main>
            <el-card class="box-card">
                <div slot="header" class="clearfix" style="padding-left: 0;">
                    <el-form ref="stockTransferForm" :rules="rules" :model="formData" label-width="100px" v-enterToNext>
                        <el-row :gutter="15">
                            <el-col :span="8">
                                <el-form-item label="调拨单号" prop="code">
                                    <el-input v-model="formData.code" clearable :disabled="!isEditFlag" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="调出仓库" prop="from_warehouse_sid">
                                    <remote-select v-model="formData.from_warehouse_sid" :options="wareHouseProps"
                                                   style="width: 100%" :disabled="!isEditFlag" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="调入仓库" prop="to_warehouse_sid">
                                    <remote-select v-model="formData.to_warehouse_sid" :options="wareHouseProps"
                                                   style="width: 100%" :disabled="!isEditFlag" />
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="15">
                            <el-col :span="24">
                                <el-form-item label="备注" prop="note_info">
                                    <el-input type="textarea" v-model="formData.note_info"
                                              clearable maxlength="300" show-word-limit :disabled="!isEditFlag" />
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-form>
                </div>
                <div class="card_content">
                    <vxeTableTemplate :data="dataList" :options.sync="tableOptions" />
                </div>
            </el-card>
        </el-main>
    </el-container>
</template>

<script>
import '@jxc/components/vxeTable/ProductDownDialog';

export default {
    name: "StockTransferForm",
    props: {
        row: {
            type: Object,
            default: null,
        },
        detail: {
            type: Boolean,
            default: false,
        },
    },
    data() {
        let _this = this;
        return {
            rules: {
                code: [
                    { required: true, message: "请输入调拨单号", trigger: "blur" },
                    { max: 32, message: "最大 32 位字符，内容过长，请删减", trigger: "blur", },
                ],
                from_warehouse_sid: [
                    { required: true, message: "请选择出库仓库", trigger: "change" },
                    {
                        validator: (rule, value, callback) => {
                            _this.changeValueRules(
                                rule,
                                value,
                                _this.formData.to_warehouse_sid,
                                callback
                            );
                        },
                        message: "调出仓库和调入仓库不能相同",
                        trigger: "change",
                    },
                ],
                to_warehouse_sid: [
                    { required: true, message: "请选择入库仓库", trigger: "change" },
                    {
                        validator: (rule, value, callback) => {
                            _this.changeValueRules(
                                rule,
                                _this.formData.from_warehouse_sid,
                                value,
                                callback
                            );
                        },
                        message: "调入仓库和调出仓库不能相同",
                        trigger: "change",
                    },
                ],
            },
            formData: {},
            dataList: [],
            tableOptions: {
                ref: "JxcStockTransferDialogTable",
                container: ".stock_transfer_form_container",
                showSummary: true,
                summaryArray: [ 'qty', 'amount'],
                columns: [],
                baseColumns: [
                    {
                        label: "物料",
                        prop: "goods_name",
                        align: "center",
                        editRender: {
                            name: "vProductDownDialog",
                            type: 'sale',
                            filter(row) {
                                if (!_this.formData.from_warehouse_sid) {
                                    _this.$message.warning("请选择调出仓库！")
                                }
                                return _this.$utils.isNotEmpty(_this.formData.from_warehouse_sid);
                            },
                            events: { event: _this.handleGoodsEvent },
                        },
                    },
                    {
                        label: "规格",
                        prop: "spec_name",
                        align: "center",
                    },
                    {
                        label: "价格",
                        prop: "price",
                        align: "center",
                        width: 100,
                        editRender: {
                            name: 'ElInput',
                            double: 4,
                            autofocus: 'input.el-input__inner',
                            autoselect: true,
                            events: {
                                input: _this.rewriteChangeRow,
                            },
                        },
                        formatter: (row, column, scope) => _this.formatterAmount(row, column, scope, 4),
                    },
                    {
                        label: "调拨数量",
                        prop: "qty",
                        align: "center",
                        width: 100,
                        editRender: {
                            name: 'ElInput',
                            integer: true,
                            autofocus: 'input.el-input__inner',
                            autoselect: true,
                            events: {
                                input: _this.rewriteChangeRow,
                            },
                        },
                    },
                    {
                        label: "金额",
                        prop: "amount",
                        align: "center",
                        width: 80,
                        formatter: (row, column, scope) => _this.formatterAmount(row, column, scope, 2),
                    },
                    {
                        label: "包装单位",
                        prop: "package_unit",
                        align: "center",
                        width: 80,
                    },
                    {
                        label: "备注",
                        prop: "note_info",
                        align: "center",
                        editRender: {
                            name: 'ElInput',
                        },
                    },
                ],
                operates: {
                    fixed: "right",
                    list: [
                        {
                            id: 'add1',
                            size: 'mini',
                            show: true,
                            tooltip: {
                                content: '插入',
                            },
	                        svg: {
		                        iconClass: 'icon-insert',
	                        },
                            filter: (row) => {
                                return _this.isEditFlag;
                            },
                            method: (index, row) => {
                                _this.handleAddRow(row, -1);
                            }
                        },
                        {
                            id: 'add2',
                            size: 'mini',
                            show: true,
                            tooltip: {
                                content: '追加',
                            },
	                        svg: {
		                        iconClass: 'icon-append',
	                        },
                            filter: (row) => {
                                return _this.isEditFlag;
                            },
                            method: (index, row) => {
                                _this.handleAddRow(row, 1);
                            }
                        },
                        {
                            id: 'del',
                            icon: 'fa fa-trash-o',
                            size: 'mini',
                            type: 'danger',
                            show: true,
                            tooltip: {
                                content: '删除',
                            },
                            filter: (row) => {
                                return _this.isEditFlag;
                            },
                            method: (index, row) => {
                                let dataList = _this.dataList.map(item => $.extend({}, item));
                                dataList = dataList.filter(item => item._index !== row._index);
                                _this.dataList = _this.resetIndex(dataList);
                                if (!_this.$utils.isNotEmptyList(dataList)) {
                                    _this.handleAddRow(null, 1);
                                }
                            }
                        }
                    ],
                },
                pagination: false,
            },
            oldCode: '',
            wareHouseProps: {
                remote: _this.$api.API_FindJxcStockWarehouses,
                placeholder: '选择仓库',
                optionProps: {
                    label: 'name',
                    value: 'sid',
                },
            },
        };
    },
    computed: {
        isEditFlag() {
            return !this.detail;
        },
    },
    watch: {
        row: {
            handler() {
                this.init();
            },
            deep: true,
            immediate: true,
        },
    },
    methods: {
        async init() {
            let _this = this;
            if (!_this.row) {
                return;
            }
            if (_this.$refs.stockTransferForm) {
                _this.$refs.stockTransferForm.clearValidate();
            }
            let sid = _this.$route.query.sid;
            if (_this.row && _this.$utils.isNotEmpty(_this.row.sid)) {
                sid = _this.row.sid;
            }
            if (_this.$utils.isNotEmpty(sid)) {
                await _this.initData(_this.row.sid);
            } else {
                _this.generateCode();
            }
            _this.initTableOptions();
            if (!_this.$utils.isNotEmptyList(_this.dataList)) {
                _this.handleAddRow(null, 1);
            }
        },
        initTableOptions() {
            const _this = this;
            let columns = _this.tableOptions.baseColumns.map(item => $.extend({}, item));
            let operates = $.extend({}, _this.tableOptions.operates);
            if (!_this.isEditFlag) {
                columns = columns.map(item => {
                    let obj = $.extend({}, item);
                    delete obj.editRender;
                    return obj;
                });
                operates = {};
            }
            _this.tableOptions = $.extend({}, _this.tableOptions, {
                columns, operates,
                getMaxHeight() {
                    let height = $(_this.getActiveTabsContainer()).height();
                    return height * 0.8 - 250;
                },
            });
        },
        initData(sid) {
            let _this = this;
            return _this.fetchData(_this.$api.API_GetJxcStockTransferBySid, {
                sid,
            }).then(result => {
                let resData = result.data || {};
                if (resData.item_list && resData.item_list.length > 0) {
                    resData.item_list.forEach(item => {
                        if (!item.note_info) {
                            item.note_info = '';
                        }
                    });
                }
                _this.formData = resData;
                _this.dataList = _this.resetIndex(resData.item_list);
                _this.oldCode = resData.code;
            }).catch(() => {
            });
        },
        generateCode() {
            let _this = this;
            if (_this.$utils.isNotEmpty(_this.oldCode) && _this.oldCode === _this.formData.code) {
                return;
            }
            return _this.storeDispatch('base/getAutoOrderCode', {
                rule_code: 'jxc_stock_transfer',
            }).then(data => {
                _this.formData = $.extend({}, _this.formData, {
                    code: data,
                });
                _this.oldCode = data;
                if (_this.$refs.stockTransferForm) {
                    _this.$refs.stockTransferForm.clearValidate('code');
                }
            });
        },
        rewriteChangeRow({ row, column }) {
            const _this = this;
            column = Object.assign({}, column, column.params)
            // 手动限制控制数字位数
            if (column.editRender && column.editRender.double) {
                _this.$set(row, column.prop, _this.$XEUtils.DoubleInput(row[column.prop], column.editRender.double));
            }
            if (column.editRender && column.editRender.integer) {
                _this.$set(row, column.prop, _this.$XEUtils.IntInput(row[column.prop]));
            }
            if (column.prop === 'qty') {
                if (_this.$utils.isNotEmpty(row.price)) {
                    _this.$set(row, "amount", _this.$utils.accMul(row.qty, row.price));
                }
            }
            if (column.prop === 'price') {
                if (_this.$utils.isNotEmpty(row.qty)) {
                    _this.$set(row, "amount", _this.$utils.accMul(row.qty, row.price));
                }
            }
        },
        handleAddRow(row, state = 1) {
            const _this = this;
            let dataList = _this.dataList.map(item => $.extend({}, item));
            let addData = {
                qty: null,
                note_info: null,
            };
            if (row && state <= 0) {
                let index = _this.dataList.findIndex(item => item._index === row._index);
                if (index !== -1) {
                    if (index === 0) {
                        dataList.unshift(addData);
                    } else {
                        dataList.splice(index, 0, addData);
                    }
                } else {
                    dataList.push(addData);
                }
            } else {
                dataList.push(addData);
            }
            _this.dataList = _this.resetIndex(dataList);
        },
        handleGoodsEvent(e, param) {
            const _this = this;
            let { row, column, params } = param;
            if (params.row) {
                _this.$set(row, 'goods_sid', params.row.sid);
                _this.$set(row, 'product_sid', params.row.product_sid);
                _this.$set(row, 'spec_name', params.row.spec_name);
                _this.$set(row, 'package_unit', params.row.unit);
                _this.$set(row, 'price', params.row.product_price);
                _this.$set(row, 'note_info', params.row.note_info);
                _this.$set(row, column.property, params.row.name);
                if (_this.$utils.isNotEmpty(row.qty) && _this.$utils.isNotEmpty(row.price)) {
                    _this.$set(row, 'amount', _this.$utils.accMul(row.qty, row.price));
                }
            }
        },
        getGoodsList(e) {
            const _this = this;
            return _this.fetchData(_this.$api.API_QueryJxcWarehouseGoodsList, {
                warehouse_sid: _this.formData.from_warehouse_sid,
                search_value: e.searchValue || '',
                pageNo: e.pageNo,
                pageSize: e.pageSize,
            }).catch(() => {
                return {
                    data: [],
                    page: {
                        totalRows: 0,
                        pages: 0,
                    },
                };
            });
        },
        changeValueRules (rule, value1, value2, callback) {
            if (value1 === value2) {
                callback(new Error(rule.message))
            }
            callback();
        },
        async confirm() {
            const _this = this;
            let valid = await _this.validateForm('stockTransferForm');
            if (!valid) {
                return false;
            }
            let filter = _this.dataList.filter(item => _this.$utils.isEmpty(item.product_sid));
            if (_this.$utils.isNotEmptyList(filter)) {
                _this.$message.error('订单明细不能为空');
                return false;
            }
            let subData = $.extend({}, _this.formData);
            subData.item_list = _this.dataList.map(item => {
                let obj = $.extend({}, {
                    id: item.id,
                    sid: item.sid,
                    goods_sid: item.goods_sid,
                    product_sid: item.product_sid,
                    price: item.price,
                    qty: item.qty,
                    package_unit: item.package_unit || item.goods_unit,
                    amount: item.amount,
                    note_info: item.note_info,
                });
                obj.sn = item._index + 1;
                return obj;
            });
            return _this.fetchData(_this.$api.API_SaveJxcStockTransfer, subData).then(() => {
                _this.$message.success('保存成功！');
                return true;
            }).catch(() => {
                return false;
            });
        },
    },
}
</script>

<style lang="less" rel="stylesheet/less" scoped>
.stock_transfer_form_container {
    width: 100%;
    height: 100%;
}
</style>
